package fbv.gui;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fbv.commun.dataTools.servico.ObjetoVO;
import fbv.commun.excecoes.FBVException;
import fbv.distribuidora.sistema.delegate.SistemaDelegate;
import fbv.distribuidora.sistema.servico.Sistema;

/**
 * Servlet implementation class for Servlet: ValidaLogin
 *
 */
public class ValidaLogin extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ValidaLogin() {
		super();
	}   	

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Sistema delegate = SistemaDelegate.getInstancia();
		HttpSession session;
		
		String user = request.getParameter("txtUsuario");
		String pass = request.getParameter("txtSenha");
		
		if(request.getParameter("logout") != null){
			
			session = request.getSession();
			session.removeAttribute("cliente");
			session.removeAttribute("usuario");
			
			response.sendRedirect(request.getContextPath());			
		}
		else if(request.getParameter("tipo") != null){
			
			try {
				ObjetoVO objetoVO = delegate.clienteIsValido(user, pass);
				
				session = request.getSession(true);
				session.setAttribute("cliente", objetoVO);
				session.setMaxInactiveInterval(20000);
				
				response.sendRedirect("ServletControladorDeExibicao");
				
			} catch (FBVException e) {
				
				response.sendRedirect("login.jsp");
			}
		}
		else{
			try{	
				boolean valido = delegate.usuarioIsValido(user, pass);
				String[] usuario = {user, pass};

				if(valido)
				{	
					session = request.getSession(true);
					session.setAttribute("usuario",  usuario);
					session.setMaxInactiveInterval(20000);
					
					response.sendRedirect("painelAdmin/principal.jsp");
				}
				else
				{
					response.sendRedirect("painelAdmin/");				
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}   	  	    
}